package com.example.oblandroid;

import java.util.ArrayList;
import java.util.List;

import Clases.Clientes;
import System.SystemCliente;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class ListaClientes extends Activity {

	private ListView lista;
	private EditText texto;
	
//	private SystemCliente sysCli;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_lista_clientes);
		
		lista= (ListView) findViewById(R.id.lv1);
		texto= (EditText) findViewById(R.id.ed1);
		
		final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, android.R.id.text1,
				cargarClientes());
		
		lista.setAdapter(adapter);
		
		lista.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int posicion, long id){
				seleccionarCliente(posicion);
			}
		});
		texto.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				adapter.getFilter().filter(s.toString());
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		
		}
	
	public void seleccionarCliente(int posicion){
		String item = lista.getItemAtPosition(posicion).toString();
		String[] args=item.split("-");
		int idCli = Integer.parseInt(args[3]);
		//		String nom = args[0];
		 Intent i = new Intent(this, ListaClientesDetalle.class);
		 i.putExtra("idCli", idCli);
		 startActivity(i);
	}
	public List<String> cargarClientes(){
		SystemCliente sysCli = new SystemCliente();
		
		String sentencia = "SELECT * FROM Clientes";
		ArrayList<Clientes> miLista = new ArrayList<Clientes>();
		miLista=sysCli.devolverListaClientes(sentencia, this);
		ArrayList<String> list = new ArrayList<String>();
		
		if(!miLista.isEmpty()){
			for (int i = 0; i < miLista.size(); i++) {
				list.add(miLista.get(i).getNombre() + " - "
						+ miLista.get(i).getRUT() + " - "
						+ miLista.get(i).getDireccion());
		}
	}
		return list;
	}
}